<?php
class Newsletter extends NewslettersAppModel {

	var $name = 'Newsletter';
	var $useTable = 'newsletters';
	var $validate = array(
		'subject' => VALID_NOT_EMPTY,
		'body_html'=>array(
						'rule'=>'validateBodyHtml',
						'message'=>'Please insert unsubscribe link.'
					)
	);
	
	var $hasMany = array(
			'Schedule' => array('className' => 'Newsletters.Schedule',
								'foreignKey' => 'newsletter_id',
								'dependent' => true,
								'conditions' => '',
								'fields' => '',
								'order' => 'Schedule.created DESC',
								'limit' => '',
								'offset' => '',
								'exclusive' => '',
								'finderQuery' => '',
								'counterQuery' => ''
			)
	);
	
	var $actsAs = array(
		'Cms.Metric' => array(
			array('metric' => 'NumRecords')
		)
	);	
	
	function validateBodyHtml($data)
	{
		$exploded_data = explode('[[unsubscribe_link]]',$data['body_html']);
		if(count($exploded_data) > 1)
		{
			return true;
		}
		return false;
		
	}
	
	function getNewsletterTypesInfo()
	{
		//$this->newsletterTypes = array(array("type"=>null,"label"=>__("Default"),"contentCall"=>false));
		$this->newsletterTypes = array();
		callHooks('getNewsletterTypes',null,$this);
		return $this->newsletterTypes;
	}
	
	function getNewsletterTypeOptions()
	{
		$types = $this->getNewsletterTypesInfo();
		if(!empty($types))
		{
			$types = Set::combine($types,"{n}.type","{n}.label");
		}
		$types = am(array(null=>__("Default")),$types);
		return $types;
	}
	
	function beforeSave($options = array())
	{
		if(isset($this->data[$this->alias]['newsletter_type']))
		{
			if(strlen(trim($this->data[$this->alias]['newsletter_type'])) == 0)
			{
				$this->data[$this->alias]['newsletter_type'] = null;
			}
		}
		return parent::beforeSave($options);
	}
	
	function getContentForNewsletterType($type)
	{
		$result = "";
		if($type)
		{
			$types = $this->getNewsletterTypesInfo();
			$types = Set::combine($types,"{n}.type","{n}.contentCall");
			if(array_key_exists($type, $types))
			{
				App::import("Vendor",$types[$type]);
				$handlerClassName = $types[$type];
				if(strpos($handlerClassName, ".") !== false)
				{
					list($tmp, $handlerClassName) = explode(".",$handlerClassName);
				}
				$newsletterContentHandler = new $handlerClassName;
				$result = $newsletterContentHandler->getNewsletterContents();
			}
		}
		return $result;
	}
	
}
?>